import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


public class MainClass
{

	
	
	
	
	
	// Accuracy of the ROC plot
	public static void main(String[] args)
	{
		
		if(args.length < 2 )
		{
			System.err.println("Call this program like");
			System.err.println("\tDirtyPlot <ROC-Output-file> <AccuracyAge-output-file>");
			return;
		}
		
		String output_roc = args[0];
		String output_acc = args[1];
				
		
		List<File> files = new ArrayList<File>();
		getFileList("distances", files);
		
		File firstFile = null;
		
		for(File f: files)
		{
			if(f.getName().equals("distances_0.csv"))
			{
				firstFile = f;
				break;
			}
		}
		
		// Ok, first get the ROC-Plot of the original file (specified above)
		int nrOfImg = 2639;			
		double optimumDecisionThreshold = 0.0;
		try
		{	
			System.out.print("Reading file for ROC-Plot " + firstFile+"...");
			DistanceMatrix distMat = DistanceMatrix.fromFile(firstFile, nrOfImg);			
			System.out.println("done");
			// Counts how often for a certain distance a match is detected. 
			// Note they are initialized to 0
			
			ROCData roc = new ROCData(distMat);			
			roc.storeToFile(new File(output_roc));
			optimumDecisionThreshold = roc.getOptimiumThres();
		}
		catch(IOException e)
		{
			e.printStackTrace();
			return;
		}
				
		System.out.println("Optimum Threshold from ROC-Plot is is " + optimumDecisionThreshold);			
		
		// find all files (each one represents an age)		
		// Store it in a hash-map with Age in days as key and Accuracy as value
		HashMap<Integer,Double> accuracies = new HashMap<Integer,Double>();
				
		try 
		{
			for(File f:files) // for all files, where each one represents one age
			{
				String fName = f.getName();
				fName = fName.substring(fName.lastIndexOf('_')+1, fName.length()-4);
				
				//System.out.println(fName);
				DistanceMatrix curdistMatrix;				
				curdistMatrix = DistanceMatrix.fromFile(f, nrOfImg);				
				
				AccuracyTester accTester = new AccuracyTester(curdistMatrix, optimumDecisionThreshold);			
				System.out.println("Accuracy for age " + fName + "\t" + accTester.getAccuracy());	
				
				accuracies.put(Integer.parseInt(fName), accTester.getAccuracy());								
			}
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Tree maps are ordered, better to print
		Map<Integer,Double> treeMap = new TreeMap<Integer, Double>(accuracies);
		

		try
		{
		BufferedWriter bw = new BufferedWriter(new FileWriter(output_acc));
		
		bw.append("Age in Days , Accuracy");
		bw.newLine();
		
		
		for(int key:treeMap.keySet())
		{
			bw.append(key + ", " + accuracies.get(key));
			bw.newLine();
		}
		
		bw.close();
		}
		catch(IOException e)
		{
			System.err.println("Could not write Accuracy output");
			e.printStackTrace();
		}
			
			
		
			
	}
	

	private static void getFileList(String directoryName, List<File> files)
	{
		File directory = new File(directoryName);

		File[] fList = directory.listFiles();

		for (File file : fList)
		{
			if (file.isFile())
			{
				files.add(file);
			}
			else if (file.isDirectory())
			{
				getFileList(file.getAbsolutePath(), files);
			}
		}
	}

}
